<template>
  <view class="patient-detail-page">
    <view class="page-header">
      <text class="page-title">患者档案详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit">编辑</button>
        <button class="btn btn-danger" @click="handleDelete">删除档案</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">患者姓名</text>
            <text class="value highlight">{{ patient.patient_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">性别</text>
            <text class="value">{{ patient.gender_text || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">出生日期</text>
            <text class="value">{{ formatDate(patient.birth_date) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">年龄</text>
            <text class="value">{{ calculateAge(patient.birth_date) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">身份证号</text>
            <text class="value">{{ patient.id_card || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">联系电话</text>
            <view class="value-with-badge">
              <text class="value">{{ patient.mobile || '-' }}</text>
              <view v-if="patient.mobile" :class="['verify-badge', patient.mobile_confirmed === 1 ? 'verified' : 'unverified']">
                {{ patient.mobile_confirmed === 1 ? '已认证' : '未认证' }}
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">医疗信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">血型</text>
            <text class="value">{{ patient.blood_type || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">过敏史</text>
            <text class="value">{{ formatArray(patient.allergies) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">慢性病史</text>
            <text class="value">{{ formatArray(patient.chronic_diseases) }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">紧急联系人</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">联系人姓名</text>
            <text class="value">{{ patient.emergency_contact || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">联系人电话</text>
            <text class="value">{{ patient.emergency_phone || '-' }}</text>
          </view>
        </view>
      </view>
      
      <view v-if="patient.user_info" class="detail-card">
        <view class="card-header">
          <text class="card-title">关联账户信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">用户名</text>
            <text class="value">{{ patient.user_info.username || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">昵称</text>
            <text class="value">{{ patient.user_info.nickname || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">手机号</text>
            <text class="value">{{ patient.user_info.mobile || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">账户状态</text>
            <text class="value">{{ patient.user_info.status === 0 ? '正常' : '禁用' }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(patient.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(patient.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const patientId = ref('')
const patient = reactive({
  _id: '',
  user_id: '',
  patient_name: '',
  gender: 0,
  gender_text: '',
  birth_date: null,
  id_card: '',
  mobile: '',
  mobile_confirmed: 0,
  blood_type: '',
  allergies: [],
  chronic_diseases: [],
  emergency_contact: '',
  emergency_phone: '',
  create_time: null,
  update_time: null,
  user_info: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  patientId.value = currentPage.options.id || ''
  
  if (!patientId.value) {
    uni.showToast({ title: '缺少患者ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/patients/list' })
    }, 1500)
    return
  }
  
  await loadPatientData()
  loading.value = false
})

async function loadPatientData() {
  try {
    const dhPatients = uniCloud.importObject('dh-patients')
    const result = await dhPatients.getPatientById(patientId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(patient, result.data)
    } else {
      throw new Error(result.message || '患者档案不存在')
    }
  } catch (err) {
    console.error('加载患者数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/patients/list' })
    }, 1500)
  }
}

function calculateAge(birthDate) {
  if (!birthDate) return '-'
  const birth = new Date(birthDate)
  const today = new Date()
  let age = today.getFullYear() - birth.getFullYear()
  const monthDiff = today.getMonth() - birth.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--
  }
  return age >= 0 ? `${age}岁` : '-'
}

function formatDate(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function formatArray(arr) {
  if (!arr || !Array.isArray(arr) || arr.length === 0) return '无'
  return arr.join('、')
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/patients/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/patients/edit?id=${patientId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此患者档案吗？删除后无法恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          const dhPatients = uniCloud.importObject('dh-patients')
          const result = await dhPatients.deletePatient(patientId.value)
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/patients/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
          }
        } catch (err) {
          console.error('删除失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.patient-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-weight: bold;
    color: #007aff;
  }
}

.value-with-badge {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.verify-badge {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  font-weight: 500;
  white-space: nowrap;
  
  &.verified {
    background: #d1fae5;
    color: #065f46;
  }
  
  &.unverified {
    background: #fee2e2;
    color: #991b1b;
  }
}
</style>

